package hbaseclipse.views.get;

import hbaseclipse.hbase.HBaseClient;
import hbaseclipse.hbase.HBaseClientConstants;

import java.util.Map;

import org.apache.hadoop.hbase.util.Bytes;
import org.eclipse.jface.viewers.ICellModifier;
import org.eclipse.swt.widgets.TableItem;

public class DIYCellModifier implements ICellModifier {

    @Override
    public boolean canModify(Object element, String property) {
        return true;
    }

    @Override
    public Object getValue(Object element, String property) {

        if (element instanceof Map<?, ?>) {
            Map<?, ?> beanMap = (Map<?, ?>) element;
            if (HBaseClientConstants.ROW_KEY.equals(property)) {
                return beanMap.get(HBaseClientConstants.ROW_KEY).toString();
            } else if (HBaseClientConstants.COLUMN_FAMILY_KEY.equals(property)) {
                return beanMap.get(HBaseClientConstants.COLUMN_FAMILY_KEY).toString();
            } else if (HBaseClientConstants.COLUMN_KEY.equals(property)) {
                return beanMap.get(HBaseClientConstants.COLUMN_KEY).toString();
            } else if (HBaseClientConstants.VALUE_KEY.equals(property)) {
                return beanMap.get(HBaseClientConstants.VALUE_KEY).toString();
            }
        }

        return null;
    }

    @Override
    public void modify(Object element, String property, Object value) {

        if (!HBaseClientConstants.VALUE_KEY.equals(property)) {
            return;
        }

        TableItem tableItem = (TableItem) element;
        String row = tableItem.getText(0);
        String cf = tableItem.getText(1);
        String c = tableItem.getText(2);
        String v = tableItem.getText(3);

        if (v.equals(value)) {
            return;
        }
        if (!(value instanceof String)) {
            return;
        }
        String valueString = (String) value;
        String tableName = GetView.getActiveView().tableNames.getText();
        boolean r = HBaseClient.put(tableName, Bytes.toBytesBinary(row), Bytes.toBytesBinary(cf),
            Bytes.toBytesBinary(c), Bytes.toBytesBinary(valueString));

        if (!r) {
            return;
        }
        GetView.getActiveView().handleGridRefresh();
        //tableItem.setText(3, valueString);
    }
}
